//
// Created by superlee on 2021/8/3.
//

#include "DataQueue.h"
#include "log.h"

DataQueue::DataQueue() {
    pthread_mutex_init(&mutexPacket, NULL);
    pthread_cond_init(&condPacket, NULL);

}

DataQueue::~DataQueue() {
    clearAVPacket();
}

int DataQueue::push(AVPacket *packet) {
    playStatus = true;
    pthread_mutex_lock(&mutexPacket);
    while (queuePacket.size() > 3) {
        pthread_cond_wait(&condPacket, &mutexPacket);
    }
    queuePacket.push(packet);
    pthread_cond_signal(&condPacket);
    pthread_mutex_unlock(&mutexPacket);
    return 0;
}

int DataQueue::getAVPacket(AVPacket *packet) {
    if (!playStatus) {
        return 0;
    }
    pthread_mutex_lock(&mutexPacket);
    while (queuePacket.empty()) {
        pthread_cond_wait(&condPacket, &mutexPacket);
    }
    memcpy(packet, queuePacket.front(), sizeof(AVPacket));
    queuePacket.pop();
    pthread_cond_signal(&condPacket);
    pthread_mutex_unlock(&mutexPacket);
    return 0;
}

int DataQueue::size() {
    pthread_mutex_lock(&mutexPacket);
    int num = queuePacket.size();
    pthread_mutex_unlock(&mutexPacket);
    return num;
}

void DataQueue::clearAVPacket() {
    playStatus = false;
    while (!queuePacket.empty()) {
        queuePacket.pop();
    }
    pthread_mutex_destroy(&mutexPacket);
    pthread_cond_destroy(&condPacket);
    playStatus = false;
}